class Answer < ActiveRecord::Base

  @@http_url_re = '((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))'

  belongs_to :question
  belongs_to :option, :class_name => 'QuestionOption'
  belongs_to :report_response
  belongs_to :site
  has_many :answers_question_options
  has_many :question_options, :through => :answers_question_options

  validates_length_of :value_text, :minimum => 2, :too_short => _("please enter a longer description"), :if => :should_validate_value_text

  def empty?
    if question.is_option
      question_options.empty?
    else
      self.option.nil? and value_text.blank?
    end
  end
  
  def is_yes
    self.option.code == "YES"
  rescue
    false
  end
  
  def is_no
    self.option.code == "NO"
  rescue
    false
  end
  
  def state_for(option)
    r = AnswersQuestionOption.find(:first, :conditions => {:answer_id => self, :question_option_id => option})
    r.state
  rescue
    nil
  end
  
  def should_validate_value_text
    required_for_submit = false
    
    if question.is_option
      # if other option exists and is selected, should require text
      other = answers_question_options.select{|a| a.question_option.is_other}.first
      unless other.nil?
        required_for_submit = other.state
      end
    else
      # validate only if the question isnt of type option and if it has an option
      # (value text only has sense where an option is selected)
      required_for_submit = !option.nil?
    end
    
    required_for_submit and report_response.is_submitted
  end
  
  # Returns the value_text wrapping hyperlinks in <a> tags 
  def html_value_text
    return nil if value_text.nil? 
    matcher = Regexp.new(@@http_url_re, Regexp::IGNORECASE)
    value_text.gsub(matcher, '<a href="\1">\1</a>')
  end
  
  # Returns the value_text wrapping hyperlinks in proper tags for pdf writer 
  def pdf_value_text
    return nil if value_text.nil?
    matcher = Regexp.new(@@http_url_re, Regexp::IGNORECASE)
    value_text.gsub(matcher, '<c:alink uri="\1">\1</c:alink>')
  end
  
end
